var _currentdate;
function plusReady() {
    var user = userLogin();
    var currentdate = new Date();
    _currentdate = currentdate.getFullYear() + "-" + currentdate.getMonth() + "-" + currentdate.getDate();
    $("#end_time").valueAsDate = new Date();

    //绑定上传图片事件
    bindImage();
    //初始化添加商品事件
    init(user);
}
if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

//$(document).ready(function(){
//    //绑定上传图片事件
//    bindImage();
//    //初始化上传事件 
//    init();
//});


function bindImage() {

	//选择时间
	$("#end_time").on("click",function(event){
		event.preventDefault();
		plus.nativeUI.pickDate( function(e){
			var d = e.date;
//			console.log(d.Format('yyyy-MM-dd'));
			$("#end_time").val(d.Format('yyyy-MM-dd'));
		},function(e){
			console.log( "未选择日期："+e.message );
		},{title:"请选择到期时间",minDate:new Date()});	
	});
	
    //取消上传
    $("#cancel").on("click", function () {
        $("#heisebg").removeClass("heisebg").addClass("heisebghid");
    });
    //从相册中选择上传
    $("#album").on("click", function () {
        var type = plus.storage.getItem("upload_goods_image");
        plus.gallery.pick(
            function (path) {
                //选择成功
                $("#heisebg").removeClass("heisebg").addClass("heisebghid");
                $("#waitingupload").removeClass("heisebghid").addClass("heisebg");
                var task = plus.uploader.createUpload(configManager.RequstUrl + "/api/common/upload",
                    { method: "POST", blocksize: 102400, priority: 100 },
                    function (upload, status) {
                        // 上传完成
                        if (status == 200) {
                            var data = JSON.parse(upload.responseText);
                            var src = configManager.goodsImgurl.format(data.id, "") + '500-200';
                            if ("addspic" == type) {
                                var sImageStr = "<img width='98%' onclick='javascript:$(this).remove();' class='spic' title='{0}' src='{1}'>";
                                $("#addspic").before(sImageStr.format(data.id, src));
                            }
                            if ("addbpic" == type) {
                                var bImageStr = "<img width='98%' id='bpic' title='{0}' onclick='javascript:$(this).remove();' src='{1}'/>";
                                $("#addbpic").children().before(bImageStr.format(data.id, src));
                            }
                            console.log(src);
                            myScroll.refresh();
                            $("#waitingupload").removeClass("heisebg").addClass("heisebghid");
                            try { myScroll.refresh(); } catch (err) { }
                        } else {
                            console.log("Upload failed: " + status);
                        }
                    }
                );
                task.addFile(path, { key: "file" });
                task.addData("dir", "goods");
                task.start();
            },
            function (e) {
                console.log(e);
            },
            { filter: "image" }
        );
    });
    //调用相机拍摄并上传
    $("#camera").on("click", function () {
        var type = plus.storage.getItem("upload_goods_image");
        var cmr = plus.camera.getCamera(1);
        if (null != cmr) {
            //拍照
            cmr.captureImage(function (p) {
                plus.io.resolveLocalFileSystemURL(
                p,
                function (entry) {
                    //拍摄成功
                    $("#heisebg").removeClass("heisebg").addClass("heisebghid");
                    $("#waitingupload").removeClass("heisebghid").addClass("heisebg");
                    //上传图片
                    var task = plus.uploader.createUpload(configManager.RequstUrl + "/api/common/upload",
                        { method: "POST", blocksize: 102400, priority: 100 },
                        function (upload, status) {
                            // 上传完成
                            if (status == 200) {
                                var data = JSON.parse(upload.responseText);
                                var src = configManager.goodsImgurl.format(data.id, "") + '500-200';
                                if ("addspic" == type) {
                                    var sImageStr = "<img class='spic' width='98%' onclick='javascript:$(this).prev().remove();$(this).remove();' title='{0}' src='{1}'>";
                                    $("#addspic").before(sImageStr.format(data.id, src));
                                }
                                if ("addbpic" == type) {
                                    var bImageStr = "<img id='bpic' width='98%' title='{0}' onclick='javascript:$(this).prev().remove();$(this).remove();' src='{1}'/>";
                                    $("#addbpic").before(bImageStr.format(data.id, src));
                                }
                                $("#waitingupload").removeClass("heisebg").addClass("heisebghid");
                                try { myScroll.refresh(); } catch (err) { }

                            } else {
                                console.log("Upload failed: " + status);
                            }
                        }
                    );
                    task.addFile("file://" + entry.fullPath, { key: "file" });
                    task.addData("dir", "store");
                    task.start();

                },
                function (e) {
                    plus.ui.alert(e.message, function () { }, configManager.alerttip, configManager.alertCtip);
                }
                );
            },
            function (e) { },
            { filename: "_doc/camera/" });
        }
        else {
            plus.ui.alert("没有找到摄像头", function () { }, configManager.alerttip, configManager.alertCtip);
        }
    });

    //图文消息
    $("#addspic").on("click", function () {
        if (5 > $(".spic").length) {
            $("#heisebg").removeClass("heisebghid").addClass("heisebg");
            plus.storage.setItem("upload_goods_image", "addspic");
        }
    });


    //商品大图
    $("#addbpic").on("click", function () {
        if (1 > $("#bpic").length) {
            $("#heisebg").removeClass("heisebghid").addClass("heisebg");
            plus.storage.setItem("upload_goods_image", "addbpic");
        }

    });

    // 
    $("input[name=type]").on("click", function () {

        if (["1", "2"].indexOf($(this).val()) > -1) {
            $("#gourpgoodslimit").show();
            if ("1" == $(this).val()) { $(".presell").show(); }
            if ("2" == $(this).val()) { $(".presell").hide(); }
        } else {
            $("#gourpgoodslimit").hide();
        }

        try { myScroll.refresh(); } catch (err) { }
    });

    // 本单详情
    $("#goodscontentinput").on("click", function () {
        var textbox = plus.webview.create("../../common/textbox.html", "../../common/textbox.html", {}, { textboxid: "goodscontent", textboxvalue: $("#goodscontent").val() });
        textbox.show("pop-in");
    });

    // 本单详情
    $("#noticeinput").on("click", function () {
        var textbox = plus.webview.create("../../common/textbox.html", "../../common/textbox.html", {}, { textboxid: "notice", textboxvalue: $("#notice").val() });
        textbox.show("pop-in");
    });
    
}

// 获取文本内容
function getMessage(id, value) {
    $("#" + id).val(value);
    $("#" + id + "input").val(convertStr(value));
}

function init(user) {
    $("#addgoods").on("click", function () {
        if ("" == $("#title").val().trim()) {
            plus.ui.alert("请输入商品名称", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }
        if ("" == $("#price").val().trim()) {
            plus.ui.alert("请输入商品价格", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }
        if ("" == $("#market_price").val().trim()) {
            plus.ui.alert("输入商品原价", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }
        if (!is_positiveinteger($("#stock").val().trim())) {
            plus.ui.alert("库存请输入正整数", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }
        if (0 > $(".spic").length) {
            plus.ui.alert("请上传商品图片", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }
        if (0 > $("#bpic").length) {
            plus.ui.alert("请上传商品大图", function () { }, configManager.alerttip, configManager.alertCtip);
            return false;
        }

        var goods = {};
        goods.type = $("input[name='type']:checked").val().trim();
        goods.title = $("#title").val().trim();
        goods.market_price = $("#market_price").val().trim();
        goods.price = $("#price").val().trim();
        goods.pic = $("#bpic").attr("title");
        //团购商品，预售商品
        if (["1", "2"].indexOf(goods.type) > -1) {
            goods.pics = [];
            $.each($(".spic"), function (i, item) {
                goods.pics.push($(item).attr("title"));
            });
            if ("" != $("#goodscontent").val().trim()) {
                goods.content = $("#goodscontent").val().trim();
            }
            if ("" != $("#notice").val().trim()) {
                goods.notice = $("#notice").val().trim();
            }
            goods.stock = $("#stock").val().trim();
            //团购商品
            if (["1"].indexOf(goods.type) > -1) {
                goods.any_time_refund = $("input[name='any_time_refund']:checked").val();
                goods.over_time_refund = $("input[name='over_time_refund']:checked").val();
                goods.end_time = $("#end_time").val() ? $("#end_time").val() : _currentdate;
            }
        }

        var postdata = { "userid": user.id, "token": user.token, "goods": goods };

        $.ajax({
            type: "POST",
            url: configManager.RequstUrl + "/api/goods/add",
            async: true,
            data: postdata
        }).done(function (data) {
            if ("success" == data.state) {
                plus.nativeUI.alert(data.message);
                plus.webview.currentWebview().opener().close();
                plus.webview.currentWebview().close();
                plus.webview.getWebviewById("shop/myshop.html").evalJS("Init()");
            }
            else {
            	plus.ui.alert(data.errors, function() { }, configManager.alerttip, configManager.alertCtip);
				//console.log(JSON.stringify(data.errors));
            }
        });

    });
}


var myScroll;
function loaded() {
    myScroll = new iScroll('wrapper', {
        useTransform: false,
        hideScrollbar: true,
        vScrollbar: true,
        fadeScrollbar: true,

        onBeforeScrollStart: function (e) {
            var target = e.target;
            while (target.nodeType != 1) target = target.parentNode;

            if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
                e.preventDefault();
        }
    });
}

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);

// 处理字符串过长情况
function convertStr(str) {
    if (str && str.length > 12) {
        return str.substr(0, 10) + "...";
    }

    return str;
}
